#!/bin/bash
# 包含GMT自带脚本文件 其中包含了一些有用的功能 比如获取网格文件的范围
. gmt_shell_functions.sh
# 本脚本的功能为显示一个规则网的三列数据
# 我们会用到之前编写的另几个脚本来生成结果图片 这里专门提供了一个参数来传递参数到调用的相应脚本中

data='null'
range='null'
overwriteRange='null'
overwrite=0
interval='null'
cols='0,1,2'
script='null'
outname='null'
geoframe=0
nogridfile=0
while getopts "ht:o:r:i:c:s:gn" arg
do
	case $arg in
		h)
			printf "plot xyz like data \nAuthor: Yi Zhang (zhangyi.cugwuhan@gmail.com)\n" 
			printf "usage: ${0##*/} -t<table-file> -i<interval>/<interval> [-o<outfile-name>] [-r<w>/<e>/<s>/<n>] [-c<col0>,<col1>,<col2>...] [-s<scripts>] [-g] [-n] \n"
			printf "%s\t%s\n" "-t" "input table file."
			printf "%s\t%s\n" "-o" "output file name, the input table name will be used if this option is absent."
			printf "%s\t%s\n" "-i" "data intervals in x and y directions."
			printf "%s\t%s\n" "-r" "data range. The template will ditect the input data range automaticly, the use of this option will overwrite the range."
			printf "%s\t%s\n" "-c" "select data columns will be used for plotting, the default is 0,1,2."
			printf "%s\t%s\n" "-s" "additional commands that will be pasted down to plotting scripts."
			printf "%s\t%s\n" "-g" "the default poltting script used here is \"gmtxy-image\", set -g option to use \"gmtsph-regional\"."
			printf "%s\t%s\n" "-n" "do not save .nc file, the default will save a output .nc grid file."
			exit 0;;
		t)
			data=$OPTARG;;
		o)
			outname=$OPTARG;;
		i)
			interval=$OPTARG;;
		r)
			overwrite=1
			overwriteRange=$OPTARG;;
		c)
			cols=$OPTARG;;
		s)
			script=$OPTARG;;
		g)
			geoframe=1;;
		n)
			nogridfile=1;;
		?)
			printf "error: unknow argument\nuse -h option to see help information\n"
			exit 1;;
	esac
done

if [[ $data == 'null' || $interval == 'null' ]]; then
	printf "error: no input file name or no -i option setted\nuse -h option to see help information\n"
	exit 1
else
	if [[ $outname == 'null' ]]; then
		ncfile=${data%.*}.nc
	else
		ncfile=${outname}
	fi
	# 获取网格范围
	if [[ $overwrite == 1 ]]; then
		range=${overwriteRange}
	else
		range=$(gmt_get_region ${data})
	fi

	xyz2grd ${data} -G${ncfile} -R${range} -I${interval} -i${cols}
	if [[ $geoframe == 1 ]]; then
		if [[ $script == 'null' ]]; then
			gmtsph-regional -i ${ncfile}
		else
			gmtsph-regional -i ${ncfile} ${script}
		fi
	else
		if [[ $script == 'null' ]]; then
			gmtxy-image -i ${ncfile}
		else
			gmtxy-image -i ${ncfile} ${script}
		fi
	fi

	if [[ $nogridfile == 1 ]]; then
		rm ${ncfile}
	fi
fi